﻿using Lcygcc.Domain.Repository.Entity.JKModel;
using Lcygcc.Infrastructure.Logs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Lcygcc.Domain.Common
{
    public class HttpService
    {
        public static string PostRequest(string strUrl, Encoding code, string strParams, int timeOut = 6)
        {

            byte[] bytes = code.GetBytes(strParams);
            string ReceviceString = "获取信息发生异常";
            try
            {
                Logger.Debug(string.Format("-----HttpService请求接口,Url地址：{0}，Params参数：{1}", strUrl, strParams));
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Method = "post";
                myReq.ContentType = "application/json";
                //myReq.Headers.Add("sn", sn);
                myReq.Timeout = timeOut * 1000;


                myReq.ContentLength = bytes.Length;
                Stream requestStream = myReq.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();

                HttpWebResponse myResponse = (HttpWebResponse)myReq.GetResponse();
                Stream responseStream = myResponse.GetResponseStream();


                StreamReader reader = new StreamReader(responseStream, code);
                StringBuilder responseData = new StringBuilder();

                string line = "";
                while ((line = reader.ReadLine()) != null)
                {
                    responseData.Append(line);
                }

                responseStream.Close();
                ReceviceString = responseData.ToString();
                Logger.Debug(string.Format("-----HttpService请求返回参数：{0}", ReceviceString));
            }
            catch (Exception ex)
            {
                Logger.Debug("-----HttpService请求接口报错：", ex);
                JKResponse response = new JKResponse();
                response.code = 9999;
                response.msg = ex.ToString();
                ReceviceString = JsonConvert.SerializeObject(response);
            }

            return ReceviceString;
        }
    }
}
